<?php

namespace app\common\model\Post;

use think\Model;
use traits\model\SoftDelete;

class Post extends Model
{
    use SoftDelete;

    //标志当前模型操作的是哪张表
    protected $name = "post";

    //开启自动写入
    protected $autoWriteTimestamp = true;

    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'createtime_text',
        'status_text',
        'comment_text',
        'collect_text'
    ];

    // 时间获取器方法
    public function getCreateTimeTextAttr($value, $data)
    {
        // 获取时间
        $createtime = isset($data['createtime']) ? trim($data['createtime']) : '';

        // 判断是否为空，不为空就转换为时间戳
        if (empty($createtime)) {
            return '';
        }
        return date('Y-m-d H:i', $createtime);
    }

    // 状态获取器
    public function getStatusTextAttr($value, $data)
    {
        $statuslist = [
            0 => '未解决',
            1 => '已解决'
        ];

        // 获取状态
        $status = isset($data['status']) ? trim($data['status']) : '';

        return $statuslist[$status];
    }

    // 评论获取器
    public function getCommentTextAttr($value, $data)
    {
        $postid = $data['id'];

        // 获取评论数（但一个人评论多次也算一次）
        $count = model('Post.Comment')->where(['postid' => $postid])->group('busid')->count();

        return $count ? $count : 0;
    }

    // 收集获取器
    public function getCollectTextAttr($value, $data)
    {
        $postid = $data['id'];

        $count = model('Post.Collect')->where(['postid' => $postid])->count();

        return $count ? $count : 0;
    }


    public function business()
    {
        return $this->belongsTo('app\common\model\Business\Business', 'busid', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function cate()
    {
        return $this->belongsTo('app\common\model\Post\Cate', 'cateid', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function collect()
    {
        return $this->belongsTo('app\common\model\Post\Collect', 'id', 'postid', [], 'LEFT')->setEagerlyType(0);
    }
}
